package com.dark.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dark.dao.mapper.JCacheMapper;
import com.dark.model.po.JCache;
import com.dark.service.IJCacheService;
import com.dark.util.TimeUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author chengluchao
 * @since 2023-08-26
 */
@Slf4j
@Service
public class JCacheServiceImpl extends ServiceImpl<JCacheMapper, JCache> implements IJCacheService {

    @Override
    @Transactional
    public void set(String key, String value) {
        set(key, value, 1000L * 60 * 60 * 24 * 365 * 100);
    }

    @Override
    @Transactional
    public void set(String key, String value, long timeOut) {
        if (log.isInfoEnabled()) {
            log.info("缓存key-{},value-{}", key, value);
        }
        baseMapper.delete(new LambdaQueryWrapper<JCache>().eq(JCache::getKey, key));
        baseMapper.insert(JCache.builder()
                .key(key)
                .value(value)
                .createTime(LocalDateTime.now())
                .updateTime(LocalDateTime.now())
                .expirationTime(TimeUtil.getFutureDateTime(timeOut, ChronoUnit.MILLIS))
                .build());
    }

    @Override
    @Transactional
    public String get(String key) {
        JCache cache = baseMapper.selectOne(new LambdaQueryWrapper<JCache>().eq(JCache::getKey, key));
        if (cache == null) {
            return null;
        }
        LocalDateTime now = LocalDateTime.now();
        if (cache.getExpirationTime().compareTo(now) < 0) {
            baseMapper.deleteById(cache.getId());
            return null;
        }
        return cache.getValue();
    }

    @Override
    public void del(String key) {
        baseMapper.delete(new LambdaQueryWrapper<JCache>().eq(JCache::getKey, key));
    }
}
